package com.servlet.login.root.utils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class UserLoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) {
        System.out.println("过滤器初始化");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("过滤器开始执行");
        //set charset utf8
        HttpServletRequest request=(HttpServletRequest)servletRequest;
        HttpServletResponse response=(HttpServletResponse)servletResponse;
        request.setCharacterEncoding("utf-8");

        //check the session name
        StringBuffer requestURL = request.getRequestURL();
        Object username = request.getSession().getAttribute("username");
        if (null == username && requestURL.toString().endsWith("success.jsp")){
            System.out.println("您还没有登陆，不可以访问success.jsp,请先登录！");
            request.getRequestDispatcher("/error.jsp").forward(servletRequest,servletResponse);
            return;
        }
        request.getRequestDispatcher("/success.jsp").forward(servletRequest,servletResponse);
//        //continue run the filter chain
//        doFilter(servletRequest,servletResponse,filterChain);
        System.out.println("过滤器结束");
    }

    @Override
    public void destroy() {
        System.out.println("过滤器销毁");
    }
}
